<?php

// +----------------------------------------------------------------------

// | Description: 客户

// +----------------------------------------------------------------------

// | Author: zl

// +----------------------------------------------------------------------



namespace app\crm\controller;



use app\admin\controller\ApiCommon;

use app\crm\model\AddCaseModel;
use app\crm\model\BalanceLog;

use app\crm\model\Setting;

use app\crm\model\SettingCategory;

use app\crm\model\Service;

use app\crm\model\ReturnVist;

use app\crm\model\ReturnVistT;

use app\crm\model\SendMsgModel;

use app\crm\model\Customer as CustomerModel;

use app\crm\model\TransferShop;

use app\crm\model\CustomerConfig as CustomerConfigModel;

use app\crm\model\CustomerGrade as CustomerGradeModel;

use app\crm\model\ReserveandLost;

use app\shop\model\Order;
use Kingdee\Kingdee;
use think\response\Json;

use think\facade\Db;

use think\facade\Request;

use app\admin\model\Coupon as CouponModel;

use app\common\traits\ActionRecordTrait;

use app\shop\model\unionpay\AppConfig;
use app\shop\model\unionpay\AppUtil;
use app\shop\model\unionpay\Test;
use app\crm\model\MiniProgramModel;
use app\shop\model\RefundPayModel;


class Ztool extends ApiCommon
{
    protected $customerModel;

    protected $customerConfigModel;

    /**

     * 用于判断权限

     * @permission 无限制

     * @allow 登录用户可访问

     * @other 其他根据系统设置

     **/

    public function initialize()

    {

        $action = [

            'permission' => ['update_customer','customer','sendyxk','change_service_time','verify_kkmoney1','verify_kkmoney','dispose_service_data','check_service_log','wx_send','daochu_wenjuan','shophufpt','update_paiban','shop_customer_type','renjun','mini_cj_customer','add_account','case_updata','order_goods','daochugoods','daochu_case','daochu_excellentcase','delete_k3','zidingyi1','rollback_case','prestored_open','chuliyucunshuju'],

            'allow' => ['users', 'info']

        ];

        event('CheckAuth',$action);

        $request = $this->request;

        $a = strtolower($request->action());



        $this->customerModel = new CustomerModel();

        $this->customerConfigModel = new CustomerConfigModel();

        if (!in_array($a, $action['permission'])) {

            parent::initialize();

        }

    }

    public function customer(){


        echo "customer";

        $a = [];
        $customer = \app\crm\model\Customer::with(['info'=>function($query)use($a){
            $query->field('id,one_time,two_time,three_time,four_time,five_time,type_store');
        },'account'=>function($query)use($a){
            $query->field('id,all_balance');
        }])->field('id,customer_name,telephone,birthday,cj_time,cj_money,source_id,create_time,sex,age')->select()->toArray();




        $setting = Setting::cache(true)->column('name','id');

        $list = [];
        $customerModel = new \app\crm\model\Customer();
        foreach ($customer as $key => $val) {
            $one = [];
            $one['create_time'] = $val['create_time'];
            $one['customer_name'] = $val['customer_name'];
            $one['telephone'] = $val['telephone'];
            $one['age'] = $val['age'];
            $one['sex'] = $val['sex'] ==1 ? '男' : '女';
//                $cj = DB::name('shop_refund_order')->where('status',2)->where('uid',$val['id'])->order('id')->field('deal_time,total_amount')->find();
            $one['cj_time'] = !empty($val['cj_time'])?date('Y-m-d',$val['cj_time']):'';
            $one['cj_money'] =$val['cj_money'];
            $one['source_type'] = isset($setting[$val['source_id']])?$setting[$val['source_id']]:'';
            $one['one_time'] = !empty($val['info']['one_time'])?$val['info']['one_time']:'';
            $one['two_time'] = !empty($val['info']['two_time'])?$val['info']['two_time']:'';
            $one['ljxf'] = !empty($val['account']['all_balance'])?$val['account']['all_balance']:'';
            array_push($list,$one);
        }


        $callName = [
            'create_time' => '录入时间',
            'customer_name' => '客户姓名',
            'telephone' => '电话',
            'sex' => '性别',
            'age'=>'年龄',
            'source_type'=>'来源',
            'cj_time' => '成交时间',
            'cj_money' => '成交金额',
            'one_time' => '首诊时间',
            'two_time' => '复诊时间',
            'ljxf' =>'累计消费',
        ];

        $downUrl = exportExcelData('双美顾客信息',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";




    }

    public function update_customer(){
        $customer = \app\crm\model\Customer::field('id,cj_time,cj_money,cj_order_id')
            ->select()->toArray();

        foreach($customer as $k=>$v){
            if(!empty($v['cj_order_id'])){
                $cj = DB::name('shop_refund_order')->where('id',$v['cj_order_id'])->where('uid',$v['id'])->order('id')->field('deal_time,total_amount')->find();
                $one = [];
                $one['cj_money'] =!empty($cj)?$cj['total_amount']:0;
            }else{
                $cj = DB::name('shop_refund_order')->where('status',2)->where('type',3)->where('uid',$v['id'])->order('id')->field('id,deal_time,total_amount')->find();
                $one = [];
                $one['cj_time'] = !empty($cj)?$cj['deal_time']:0;
                $one['cj_money'] =!empty($cj)?$cj['total_amount']:0;
                $one['cj_order_id'] = !empty($cj)?$cj['id']:0;
            }
            DB::name('customer')->where('id',$v['id'])->update($one);
        }
        echo "处理成功";
    }




    public function check_service_log(){
        echo "检测核销记录";

        $shop_id = [73782775132896]; // zhenghongcheng

        $staff_ids = [498];

        $start_time = strtotime('2023-06-01');

        $end_time = strtotime('2023-06-30 23:59:59');

        $list1 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', 'in', $staff_ids], ['nurse_id_two', '=', 0], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_one')->column('count(*) as sum','nurse_id_one');

        echo "<pre>";
        print_r($list1);
        echo "</pre>";
        // exit;

        $list2 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', 'in', $staff_ids], ['nurse_id_two', '>', 0], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_one')->column('count(*)*0.5 as sum','nurse_id_one');

        echo "<pre>";
        print_r($list2);
        echo "</pre>";

        $list3 = Db::name('service_log')->where([['shop_id', 'in', $shop_id], ['nurse_id_one', '>', 0], ['nurse_id_two', 'in', $staff_ids], ['create_time', 'between', "$start_time,$end_time"]])->group('nurse_id_two')->column('count(*)*0.5 as sum','nurse_id_two');

        echo "<pre>";
        print_r($list3);
        echo "</pre>";

    }

    // public function (){

    //     $where = [];

    //     $shop_ids = [];

    //     $start_time = strtotime('2023-01-01 00:00:00');

    //     $end_time = strtotime('2023-12-31 23:59:59');

    //     array_push($where,[$where,['shop_id','in',$shop_ids]]);

    //     array_push($where,[$where,['status','=',1]]);

    // }

    public function wx_send()
    {

        // $gzh_openids = Db::name('mini_program_fans')->alias('m')

        // ->join('wx_gzh_fans g', 'g.unionId = m.unionId', 'LEFT')

        // ->where([['g.openid','>','0']])

        // ->column('g.openid');

        // echo "<pre>";
        // print_r($gzh_openids);
        // echo "</pre>";

        // $model = new SendMsgModel();

        // $gzh_openids = ['orXbIs5Il9x5cC9wT_kP-GzS29Wk','orXbIs9RDp16tEveSqcWIYB82R6c'];

        // echo "<pre>";
        // print_r($gzh_openids);
        // echo "</pre>";
        // // exit;

        // $num = 0;
        // foreach ($gzh_openids as $key => $value) {
        //     $model->wx_send_cs($value,0);
        //     $num++;
        // }

        // echo "发送".count($gzh_openids).'-成功'.$num;


        echo '1122244';
        // 直管店客户批量转店
        // $customer_ids = Db::name('customer')->where('shop_id','78852616335812')->column('id');
        $where = [];
        array_push($where,['shop_id','=','79154893551569']);
        // array_push($where,['king_no','like','30131%']);
        $customer_ids = Db::name('customer')->where($where)->column('id');

        // echo "<pre>";
        // print_r($customer_ids);
        // echo "</pre>";
        // exit;

        $start_time = strtotime('2024-06-01 00:00:00');
        $end_time = strtotime('2024-06-04 23:59:59');
        $tag_shop_id = '73782774822370';
        foreach ($customer_ids as $key => $value) {
            // 修改客户归属门店
            Db::name('customer')->where('id','=',$value)->update(['shop_id'=>$tag_shop_id]);

            // 修改客户预存门店归属
            Db::name('customer_balance')->where('customer_id','=',$value)->update(['shop_id'=>$tag_shop_id]);

            // 修改客户卡项
            Db::name('service')->where('customer_id','=',$value)->update(['shop_id'=>$tag_shop_id]);

            // 修改客户核销记录
            //Db::name('service_log')->where([['customer_id','=',$value],['create_time','between',"$start_time,$end_time"]])->update(['shop_id'=>$tag_shop_id]);
        }

        echo 'end';
    }

    public function daochu_wenjuan(){
        // echo 'daochu_wenjuan';

        $param = [
            'is_export' => 1,
            'create_time_start' => '',
            'create_time_end' => '',
            'feed_type' => '',
            'limit' => 10,
            'page' => 1,
            'shop_id' => '',
            'total' => 0,
            'wenjuanID' => 6,
            'wenjuan_id' => 6,
        ];

        $model = new MiniProgramModel();

        $data = $model->getManyiduList($param);

        // echo "<pre>";
        // print_r($data);
        // echo "</pre>";

        $title = '满意度明细导出';

        $downUrl = exportExcelData($title,$data['callName'],$data['list'],'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }

    public function update_paiban(){
        echo "update_paiban";

        // $delete_where = [];

        // array_push($delete_where,['time','=','20240103']);

        // Db::name('customer_balance_tj')->where($delete_where)->delete();
        // $where = [];

        // array_push($where,['time','like','202301%']);
        // // array_push($where,['shop_person_id','=','13']);

        // $errorList = Db::name('shop_person_schedule')->where($where)->select()->toArray();

        // echo "<pre>";
        // print_r($errorList);
        // echo "</pre>";

        // foreach ($errorList as $key => $value) {
        //     $year = substr($value['time'],0,4);
        //     $mon = substr($value['time'],4,2);
        //     $day = substr($value['time'],6,2);

        //     $newYear = $year+1;

        //     echo $rightDate = $newYear.$mon.$day;
        //     echo "<br/>";

        //     Db::name('shop_person_schedule')->where('id','=',$value['id'])->update(['time'=>$rightDate]);


        // }

    }

    public function shop_customer_type()
    {

        // $title = ['71'=>'C','72'=>'B','73'=>'A'];

        $where = [];

        array_push($where,['type','=','1']);
        array_push($where,['shop_name','not in','营销中心']);
        array_push($where,['status','=','1']);
        array_push($where,['market_id','in',[4,6]]);

        $shop_list = DB::name('shop')->where($where)->column('shop_id');

        // 门店
        $shop_names = Db::name('shop')->where([['shop_id', 'in', $shop_list]])->column('shop_name','shop_id');

        // $type = '71';

        $start_time = strtotime('2023-01-01');
        $end_time = strtotime(2024-01-01);

        $list = [];
        foreach ($shop_list as $key => $value) {
            $where = [];

            array_push($where,['member_classification','in',[71,72,73]]);
            array_push($where,['shop_id','=',$value]);
            array_push($where,['final_consumption','between',"$start_time,$end_time"]);

            $res = Db::name('customer')->where($where)->column('id');

            // echo "<pre>";
            // print_r($res);
            // echo "</pre>";
            // exit;

            $a = 0;
            $b = 0;
            $c = 0;
            foreach ($res as $k => $v) {

                $where = [];

                array_push($where,['uid','=',$v]);
                array_push($where,['type','=','3']); // 收款单
                array_push($where,['refund_type','=','101.02']);
                array_push($where,['status','=','2']);
                array_push($where,['deal_time','between',"$start_time,$end_time"]);

                $money1 = Db::name('shop_refund_order')->where($where)->value('SUM(pay_amount)');

                $money1 = $money1 ?? '0.00';

                $where = [];

                array_push($where,['uid','=',$v]);
                array_push($where,['type','=','1']); // 退款单
                array_push($where,['refund_type','=','101.02']);
                array_push($where,['status','=','2']);
                array_push($where,['deal_time','between',"$start_time,$end_time"]);

                $money2 = Db::name('shop_refund_order')->where($where)->value('SUM(pay_amount)');

                $money2 = $money2 ?? '0.00';

                $consumption = bcsub($money1,$money2,2);

                switch ($consumption)
                {
                    case $consumption >= 50000: // A类客户
                        $a++;
                        break;
                    case $consumption >= 15000: // B类客户
                    // case $consumption < 50000:
                        $b++;
                        break;
                    case $consumption >= 5000: // C类客户
                    // case $consumption < 15000:
                        $c++;
                        break;
                    default:
                        break;
                }
            }

            $one = [];

            $one['shop_name'] = $shop_names[$value];
            $one['a'] = $a;
            $one['b'] = $b;
            $one['c'] = $c;

            array_push($list,$one);
        }


        // $where = [];

        // array_push($where,['member_classification','=',72]);
        // array_push($where,['shop_id','in',$shop_list]);
        // // array_push($where,['create_time','between',"$start_time,$end_time"]);

        // $res2 = Db::name('customer')->where($where)->group('shop_id')->column('count(*)','shop_id');

        // $where = [];

        // array_push($where,['member_classification','=',73]);
        // array_push($where,['shop_id','in',$shop_list]);
        // // array_push($where,['create_time','between',"$start_time,$end_time"]);

        // $res3 = Db::name('customer')->where($where)->group('shop_id')->column('count(*)','shop_id');



        // $list = [];

        // foreach ($shop_list as $key => $value) {
        //     $one = [];

        //     $one['shop_name'] = $shop_names[$value];
        //     $one['customer_type1'] = $res1[$value] ?? '';
        //     $one['customer_type2'] = $res2[$value] ?? '';
        //     $one['customer_type3'] = $res3[$value] ?? '';

        //     array_push($list,$one);

        // }

        echo "<pre>";
        print_r($list);
        echo "</pre>";
// exit;
        $callName = [

            'shop_name' =>'门店',

            'a' =>'a类顾客',
            'b' =>'B类顾客',
            'c' =>'C类顾客',

        ];

        $downUrl = exportExcelData('顾客分类统计',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";

    }

    public function renjun()
    {
        echo "renjun";

        $date = date('Y-m-d');

        $where = [];

        array_push($where,['type','in',[1,3]]);
        array_push($where,['shop_name','not in','营销中心']);
        array_push($where,['status','=','1']);
		//array_push($where,['shop_id','=','73782774707242']);

        $shop_list = DB::name('shop')->where($where)->column('shop_id');

        // echo "<pre>";
        // print_r($shop_list);
        // echo "</pre>";
        // exit;

		$start_time =strtotime($_GET['start_time']);
		$end_time=strtotime($_GET['end_time'])+86399;

		// $start_time = strtotime(date('Y-m-01'));
		// $end_time = strtotime(date('Y-m-t'))+86399;

        // echo "开始时间：".$start_time;echo "<br/>";
        // echo "结束时间：".$end_time;

        // exit;

        // 门店
        $shop_names = Db::name('shop')->where([['shop_id', 'in', $shop_list]])->column('shop_name','shop_id');

        $model = new ReserveandLost();



        $list = [];
        foreach ($shop_list as $key => $value) {

            // $customer_ids = $model->cj_customer([$value],[]);

            // $ids = $model->baoyou_customer($customer_ids,$date);

            $where = [];

            array_push($where,['shop_id','=',$value]);
            array_push($where,['type','=','3']); // 收款单
            array_push($where,['refund_type','=','101.02']);
            array_push($where,['status','=','2']);
			array_push($where,['deal_time','between',"$start_time,$end_time"]);
            array_push($where,['business_type','=','4']); // distinct

            $num4 = Db::name('shop_refund_order')->where($where)->count();

			// $num4 = Db::name('shop_refund_order')->group('uid')->where($where)->column('sum(pay_amount) as amount,shop_id,uid');

			// $numT =0;
			// foreach ($num4 as $k => $v) {

			// 	if($v['amount']>=2980){
			// 		$numT++;
			// 	}

			// }

			// echo "<pre>";
			// print_r($num4);
			// echo "</pre>";
            // $money1 = $money1 ?? '0.00';

            // $where = [];

            // array_push($where,['uid','in',$ids]);
            // array_push($where,['type','=','1']); // 退款单
            // array_push($where,['refund_type','=','101.02']);
            // array_push($where,['status','=','2']);

            // $money2 = Db::name('shop_refund_order')->where($where)->value('SUM(pay_amount)');

            // $money2 = $money2 ?? '0.00';

            // $amount = bcsub($money1,$money2,2);

            $one =[];
            $one['shop_name'] = $shop_names[$value];
            $one['num'] = $num4;

            array_push($list,$one);


        }
		//exit;
        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";exit;

        $callName = [

            'shop_name' =>'门店',

            'num' => '数量',

        ];

        $downUrl = exportExcelData('销售数量',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";

    }


	public function shophufpT()
	{
	    echo "renjun";

	    $date = date('Y-m-d');

	    $where = [];

	    array_push($where,['type','in',[1,3]]);
	    array_push($where,['shop_name','not in','营销中心']);
	    array_push($where,['status','=','1']);
		//array_push($where,['shop_id','=','73782774707242']);

	    $shop_list = DB::name('shop')->where($where)->column('shop_id');

	    // echo "<pre>";
	    // print_r($shop_list);
	    // echo "</pre>";
	    // exit;


		$start_time = 1709222400;
		$end_time = 1711900799;

	    // 门店
	    $shop_names = Db::name('shop')->where([['shop_id', 'in', $shop_list]])->column('shop_name','shop_id');

	    $model = new ReserveandLost();



	    $list = [];
	    foreach ($shop_list as $key => $value) {

	        // $customer_ids = $model->cj_customer([$value],[]);

	        // $ids = $model->baoyou_customer($customer_ids,$date);

	        $where = [];

	        array_push($where,['shop_id','=',$value]);
	        array_push($where,['type','=','3']); // 收款单
	        array_push($where,['refund_type','=','101.02']);
	        array_push($where,['status','=','2']);
			array_push($where,['deal_time','between',"$start_time,$end_time"]);
	        //array_push($where,['business_type','=','4']);  distinct

	        //$num4 = Db::name('shop_refund_order')->where($where)->count();

			$num4 = Db::name('shop_refund_order')->group('uid')->where($where)->column('sum(pay_amount) as amount,shop_id,uid');

			$numT =0;
			foreach ($num4 as $k => $v) {

				if($v['amount']>=2980){
					$numT++;
				}

			}


	        $one =[];
	        $one['shop_name'] = $shop_names[$value];
	        $one['num'] = $numT;

	        array_push($list,$one);


	    }
		//exit;
	    // echo "<pre>";
	    // print_r($list);
	    // echo "</pre>";exit;

	    $callName = [

	        'shop_name' =>'门店',

	        'num' => '数量',

	    ];

	    $downUrl = exportExcelData('累计消费金额是2980',$callName,$list,'xlsx',1);

	    echo "<script language='javascript'>";

	    echo " location='".$downUrl."';";

	    echo "</script>";

	}



    public function mini_cj_customer(){
        // echo 'mini_cj_customer';

        $customer_ids = Db::name('mini_program_fans')->alias('m')->join('customer c','c.id = m.customerId','LEFT')->where([['c.cj_money','>=','500'],['m.create_time','>','2022-12-31 23:59:59']])->column('c.id');

        // $customer_ids = Db::name('customer')->alias('c')->where([['c.cj_money','>=','500'],['c.cj_time','>=','1672502400']])->count();

        // echo $customer_ids;

        echo "<pre>";
        print_r($customer_ids);
        echo "</pre>";


        // $gzh_openids = Db::name('mini_program_fans')->alias('m')

        // ->join('wx_gzh_fans g', 'g.unionId = m.unionId', 'LEFT')

        // ->where([['g.openid','>','0']])

        // ->column('g.openid');
    }

    public function add_account(){
        // echo "新建账户";

        // $where = [];

        // array_push($where,['type','<>',2]);
        // array_push($where,['status','=',1]);
        // // array_push($where,['shop_type','=',1]); // 私户

        // $list = Db::name('shop')->where($where)->column('id,shop_name,shop_id,province_name,city_name,country_name,address,shop_gonghu_cusid,shop_gonghu_appid,shop_gonghu_privateKey');

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";

        // $callName = [

        //     'id' =>'ID',

        //     'address' => '地址',

        // ];

        // $downUrl = exportExcelData('门店信息',$callName,$list,'xlsx',1);

        // echo "<script language='javascript'>";

        // echo " location='".$downUrl."';";

        // echo "</script>";


        // exit;

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://sunburn.178590.com/return/add_account.html">返回【会员基本信息导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        $importData = readExcelData($tmp_name);

        $RefundPay = new RefundPayModel();

        $length = 8;
        // $addData = [];
        foreach ($importData as $key => $value) {


            // exit;

            $termno = str_pad($value[0], $length, "0", STR_PAD_LEFT);
            $appid = str_pad($value[8], $length, "0", STR_PAD_LEFT);

            $addtermRequest = [

                'cusid' => $value[7],

                'appid' => $appid,

                'private_key' => $value[9],

                'termno' => $termno,

                'termaddress' => $value[3].'-'.$value[4].'-'.$value[5].'-'.$value[6],

            ];

            // echo "<pre>";
            // print_r($addtermRequest);
            // echo "</pre>";

            $res = $RefundPay->addterm($addtermRequest);

            if($res['retcode'] == 'SUCCESS'){

                echo $value[1]."<br/>";
                echo "<pre>";
                print_r($res);
                echo "</pre>";

                echo "<br/>";
                echo "<br/>";

                Db::name('shop')->where('shop_id',$value[2])->update(['termno_g' => $termno]);

            }else{

                echo $value[1]."<br/>";
                echo "<pre>";
                print_r($res);
                echo "</pre>";

                echo "<br/>";
                echo "<br/>";

            }

        }

        echo 'over';

    }

    public function case_updata()
    {
        $where = [];

        $tag_time = strtotime(date('Y-m',time()));

        echo $tag_time;

        array_push($where,['sp_excellent_time','<',$tag_time]);
        array_push($where,['selection_results','=','1']);

        $case_list = Db::name('case')->where($where)->select()->toArray();

        echo "<pre>";
        print_r($case_list);
        echo "</pre>";

        // foreach ($case_list as $key => $value) {

        //     Db::name('case')->where('id','=',$value['id'])->update(['selection_results' => 4]);

        // }
    }

    public function order_goods(){
        echo "order_goods";

        $start_time = strtotime("2024-07-01 00:00:00");
        $end_time = strtotime("2024-07-31 23:59:59");

        $where = [];

        array_push($where,['so.order_amount','=','0.00']);
        array_push($where,['so.status','=',2]);
        array_push($where,['so.is_pay','=',1]);
        array_push($where,['so.deal_time','between',"$start_time,$end_time"]);

        $res = Db::name('shop_order_goods')->alias('sog')

        ->join('shop_order so', 'so.id = sog.order_id', 'LEFT')

        ->where($where)

        ->limit(16000,5000)

        ->column('so.create_time,so.uid,so.shop_id,so.order_no,so.business_type,so.order_type,so.operator_name,so.is_experience,so.is_outreach,sog.goods_name,sog.is_project,sog.category_id,sog.goods_id,sog.goods_price,sog.pay_price,sog.number,sog.service_number,sog.end_time,so.description');

		//echo count($res);exit;

        // echo "<pre>";
        // print_r($res);
        // echo "</pre>";
        // exit;

        $customer_ids = array_values(array_unique(array_column($res,'uid')));

        $customer_info = Db::name('customer')->where('id','in',$customer_ids)->column('customer_name,telephone,sex','id');

        $shop_ids = array_values(array_unique(array_column($res,'shop_id')));

        $shop_info = Db::name('shop')->where('shop_id','in',$shop_ids)->column('shop_name,market_name','shop_id');

        // echo "<pre>";
        // print_r($shop_ids);
        // echo "</pre>";
        // exit;

        $business_type = ['1' => '疤痕','2' => '项目','3' => '青春痘','4' => '护肤品'];

        $order_type = ['1' => '新单','2' => '补单'];

        $list = [];

        foreach ($res as $key => $value) {

            $one = [];

            $one['create_time'] = date('Y-m-d',$value['create_time']) ?? '';
            $one['customer_name'] = $customer_info[$value['uid']]['customer_name'] ?? '';
            $one['telephone'] = $customer_info[$value['uid']]['telephone'] ?? '';
            $one['sex'] = $customer_info[$value['uid']]['sex'] = 1 ? '男' : '女';
            $one['shop_name'] = $shop_info[$value['shop_id']]['shop_name'] ?? '';
            $one['market_name'] = $shop_info[$value['shop_id']]['market_name'] ?? '';
            $one['order_no'] = $value['order_no'] ?? '';
            $one['business_type'] = $business_type[$value['business_type']] ?? '';
            $one['order_type'] = $order_type[$value['order_type']] ?? '';
            $one['operator_name'] = $value['operator_name'] ?? '';
            $one['is_experience'] = $value['is_experience'] == 1 ? '是' : '否';
            $one['is_outreach'] = $value['is_outreach'] == 1 ? '是' : '否';
            $one['goods_name'] = $value['goods_name'] ?? '';
            $one['is_project'] = $value['is_project'] == 1 ? '服务' : '商品';
            $one['goods_price'] = $value['goods_price'] ?? '';
            $one['pay_price'] = $value['pay_price'] ?? '';
            $one['number'] = $value['number'] ?? '';
			$one['description'] = $value['description'] ?? '';
            $one['service_number'] = $value['service_number'] ?? '';
            $one['end_time'] = $value['end_time'] > 0 ? date('Y-m-d',$value['end_time']) : '';

            array_push($list,$one);
        }

        // echo "<pre>";
        // print_r($list);
        // echo "</pre>";

        $callName = [

            'create_time' => '录入时间',
            'customer_name' => '客户姓名',
            'telephone' => '电话',
            'sex' => '性别',
            'shop_name' => '门店',
            'market_name' => '市场',
            'order_no' => '订单编号',
            'business_type' => '业务类型',
            'order_type' => '订单类型',
            'operator_name' => '录单员',
            'is_experience' => '是否体验',
            'is_outreach' => '是否外联',
            'goods_name' => '商品名称',
            'is_project' => '商品类型',
            'number' => '数量',
            'goods_price' => '标准单价',
            'pay_price' => '销售单价',
            '' => '销售金额',
            'service_number' => '开卡次数',
            'end_time' => '到期时间',
			'description' => '备注',

        ];

        $downUrl = exportExcelData('0元单导出记录明细',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }

    public function daochugoods(){
        echo "daochugoods";

        // $start_time = strtotime("2024-03-01 00:00:00");
        // $end_time = strtotime("2024-03-31 23:59:59");

        $goodName = "眼部5D精雕";

        $where = [];

        array_push($where,['goods_name','=',$goodName]);

        $order_ids = Db::name('shop_order_goods')->where($where)->column('order_id');

        $where = [];

        array_push($where,['id','in',$order_ids]);
        array_push($where,['status','=',2]);
        array_push($where,['is_pay','=',1]);

        $customer_ids = Db::name('shop_order')->where($where)->column('uid');

        $list = Db::name('customer')->where('id','in',$customer_ids)->column('customer_name,telephone');

        echo "<pre>";
        print_r($list);
        echo "</pre>";
        // exit;



        $callName = [


            'customer_name' => '客户姓名',
            'telephone' => '电话',

        ];

        $downUrl = exportExcelData($goodName,$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }

    public function daochu_case()
    {
        echo "案例";

        $st = strtotime('2024-04-01 00:00:00');
        $et = strtotime('2024-05-31 00:00:00');

        $where = [];

        array_push($where,['age','between','0,18']);

        $customers = Db::name('customer')->where($where)->column('id');

        echo "<pre>";
        print_r($customers);
        echo "</pre>";
        // exit;

        $where = [];

        // array_push($where,['selection_results','in',[2,3]]);
        array_push($where,['customer_id','in',$customers]);

        $list = Db::name('case')->where($where)->count();

        echo "<pre>";
        print_r($list);
        echo "</pre>";
        exit;

        $customer_list = Db::name('customer')->where('id','in',$list)->column('customer_name,telephone');
        // echo "<pre>";
        // print_r($customer_list);
        // echo "</pre>";

        $callName = [


            'customer_name' => '客户姓名',
            'telephone' => '电话',

        ];

        $downUrl = exportExcelData('申请案例',$callName,$customer_list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }

    public function daochu_excellentcase(Request $request)
    {
        $data =  request()->param();

        $start_time = $end_time = '';
        if(isset($data['start_time'])){
            $start_time = strtotime($data['start_time']);
        }
        if(isset($data['end_time'])){
            $end_time = strtotime($data['end_time']." 23:59:59");
        }

        $where = [];
        if(!empty($start_time)){
            array_push($where,['sp_excellent_time','>=',$start_time]);
        }
        if(!empty($end_time)){
            array_push($where,['sp_excellent_time','<=',$end_time]);
        }

        array_push($where,['selection_results','IN',[2,3]]);

        $list = AddCaseModel::with(['customer'=>function($query) use($where){
            $query->field('id,customer_name,telephone');
        },'shop'=>function($query)use($where){
            $query->field('shop_id,shop_name');
        }])->where($where)->field('selection_results,shop_id,customer_id,sp_excellent_time')->select()->toArray();
        $type= [
            2=>'优秀案例',
            3=>'满意案例'
        ];
        foreach($list as $k=>&$v){
            if(!empty($v['customer'])){
                $v['customer_name'] = $v['customer']['customer_name'];
                $v['telephone'] = $v['customer']['telephone'];
            }
            if(!empty($v['shop'])){
                $v['shop_name'] = $v['shop']['shopName'];
            }
            $v['sp_excellent_time'] = date('Y-m-d H:i:s',$v['sp_excellent_time']);
            $v['type'] = isset($type[$v['selection_results']]) ?$type[$v['selection_results']]:'';
        }
        $callName = [
            'shop_name' => '门店名称',
            'customer_name' => '客户姓名',
            'telephone' => '电话',
            'type' => '优/满案例',
            'sp_excellent_time' => '申请时间',
        ];

        $downUrl = exportExcelData('申请优满案例',$callName,$list,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";
    }


    public function delete_k3(){
        $k3Code = '40303.01';

        $where = [];
        array_push($where,['king_no','like',$k3Code."%"]);

        $customer_ids = Db::name('customer')->where($where)->column('id');

        echo "<pre>";
        print_r($customer_ids);
        echo "</pre>";
        exit;

        foreach ($customer_ids as $key => $value) {
            // 清除客户K3代码
            Db::name('customer')->where('id','=',$value)->update(['king_no'=>"",'fcustId'=>""]);

        }
    }

    public function zidingyi1(){
        $where = [];

        $balance_category_id = [3,4];
        array_push($where,['balance_category_id','in',$balance_category_id]);

        $customer_ids = Db::name('customer_balance')->where($where)->group('customer_id')->column('count(*) as num, customer_id');

        $list = [];
        foreach ($customer_ids as $key => $value) {
            if($value['num'] > 2){
                // echo $value['num'];
                // echo "<br/>";
                array_push($list,$value['customer_id']);
            }
        }
        echo "<pre>";
        print_r($list);
        echo "</pre>";
        // exit;

        foreach ($list as $key => $value) {
            $where = [];

            array_push($where,['customer_id','=',$value]);
            array_push($where,['balance_category_id','in',$balance_category_id]);
            $ids = Db::name('customer_balance')->where($where)->order('id DESC')->limit(0,2)->column('id');

            $delete_where = [];

            array_push($delete_where,['id','in',$ids]);

            Db::name('customer_balance')->where($delete_where)->delete();

            // echo "<pre>";
            // print_r($ids);
            // echo "</pre>";
            // exit;
        }



    }

    public function rollback_case()
    {
        $last_mon = date('m',strtotime('-1 month'));

        $last_year =  date('Y',strtotime('-1 month'));

        $t = date('t',strtotime('-1 month'));

        $start_time = strtotime($last_year.'-'.$last_mon.'-01 00:00:00');
        $end_time = strtotime($last_year.'-'.$last_mon.'-'.$t.' 23:59:59');

        $where = [];

        array_push($where,['sp_excellent_time','between',"$start_time,$end_time"]);
        array_push($where,['selection_results','=','1']);

        $list = Db::name('case')->where($where)->select()->toArray();

        echo "<pre>";
        print_r($list);
        echo "</pre>";
        exit;

        // echo $start_time;
        // echo "<br/>";
        // echo $end_time;

    }

    //川渝市场-客户预存开放
    public function prestored_open(Request $request){
        $data =  request()->param();
        $market_id = $data['market_id']??0;
        $type = $data['type']??0;
        if(!in_array($market_id,[8,9,10,11,105])){
            echo "暂无川渝市场";die;
        }

        $map = [
            ['status','=',1],
            ['type','<>',2],
            ['market_id','=',$market_id],
//            ['shop_id','=',73782774982464]
        ];
        if($market_id == 8 and $type ==1){
            $shopids = [73782774982253,73782774973465,73782774939196];
            array_push($map,['shop_id','in',$shopids]);
        }

        if($market_id == 8 and $type ==2){
            $shopids = [73782774937394,73782774982464];
            array_push($map,['shop_id','in',$shopids]);
        }

        if($market_id == 9 and $type ==1){
            $shopids = [73782774988622,73782774957269,73782775030746];
            array_push($map,['shop_id','in',$shopids]);
        }

        if($market_id == 9 and $type ==2){
            $shopids = [73782775078712,73782775070582,79958737536305];
            array_push($map,['shop_id','in',$shopids]);
        }


        $shop = DB::name('shop')->where($map)->field('shop_id,shop_name')->select()->toArray();

        $shop_ids = array_column($shop,'shop_id');

        $shop = array_column($shop,'shop_name','shop_id');

        $customer = DB::name('customer')->whereIn('shop_id',$shop_ids)->field('id,shop_id,customer_name,telephone,is_show_balance')->select()->toArray();

        foreach ($customer as $k=>&$v){
            $v['shop_name'] = $shop[$v['shop_id']];
//            $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
//            $balance = DB::name('customer_balance')->where('customer_id',$v['id'])->where('shop_id',$v['shop_id'])->field('sum(money) as money,sum(complimentary_money) as complimentary_money,sum(shop_transfer_money) as shop_transfer_money')->find();
//            $money = bcadd($balance['money'],$balance['complimentary_money'],2);
//            $money = bcadd($money,$balance['shop_transfer_money'],2);
//            $v['money'] = $money;
            $v['is_show_balance'] = $v['is_show_balance'] == 1?'已开放':'未开放';
        }

        $title = '川渝市场客户信息';
        $list_title = [
            'shop_name'=>'门店名称',
            'customer_name'=>'顾客名称',
            'telephone'=>'手机号',
//            'king_no'=>'k3代码',
//            'money'=>'剩余预存',
            'is_show_balance'=>'是否开放预存',
//            'create_time'=>'创建时间',
        ];


        $downUrl = exportExcelData($title,$list_title,$customer,'xlsx',1);

        echo "<script language='javascript'>";

        echo " location='".$downUrl."';";

        echo "</script>";




    }


    public function chuliyucunshuju(){

        $error = [];
        $data = DB::name('customer_prestock_goods')->field('id,order_id,order_goods_id,deal_time,goods_price')->select()->toArray();

        foreach($data as $k=>$v){
            $deal_time = DB::name('shop_order')->where('id',$v['order_id'])->value('deal_time');
            $goods_price = DB::name('shop_order_goods')->where('id',$v['order_goods_id'])->value('pay_price');

            $res = DB::name('customer_prestock_goods')->where('id',$v['id'])->update(
                [
                    'deal_time'=>$deal_time,
                    'goods_price' =>$goods_price,
                ]
            );
            if(!$res){
                array_push($error,$v['id']);
            }
        }
        var_dump($error);die;

    }


    public function dispose_service_data(){

        //第一步，先把除0元单的卡项，次卡，查询出来
        $map = [
            ['status','=',1],
            ['service_type','=',2],
            ['kk_money','>',0],
//            ['id','=',419336]
        ];
//        $data = DB::name('service')->where($map)->limit(7600,200)->select()->toArray();
//        $data = DB::name('service')->where($map)->limit(100)->select()->toArray();

        $data = DB::name('service')->where($map)->limit(780,20)->select()->toArray();


        $orderModel = new Order();
        $serviceModel = new Service();
        $time = time();
        $error = [];

        foreach ($data as $k=>$v){

//            $half_num = 3;
//            $month_max = 6;
//            $enterShopData = $orderModel->getMaxCustomerEnterShop($v['start_time'],$v['end_time'],$half_num,$month_max); //最高进店次数
//            $oneService= [];
//            $oneService['is_tz'] = 1;
//            $oneService['update_time'] = $time;
//            $oneService['service_max_num'] = $enterShopData['service_max_num'];
//            $oneService['first_month_max_service_num'] = $enterShopData['shou'];
//            $oneService['middle_month_max_service_num'] = $enterShopData['zhong'];
//            $oneService['end_month_max_service_num'] = $enterShopData['wei'];
//            $res = DB::name('service')->where('id',$v['id'])->update($oneService);
//            if(!$res){
//                array_push($error,$v['id']);
//            }

//            $start_time = $v['start_time'];
//            $end_time = $v['end_time'];

//            $start_time = 1744732800; //25-04-01
//            $end_time = 1828195200;  //25-12-03

//            $v['start_time'] = 1744732800;
//            $v['end_time'] = 1828195200;

//            $startDate = new \DateTime();
//            $startDate->setTimestamp($start_time);
//            $endDate = new \DateTime();
//            $endDate->setTimestamp($end_time);
//            $interval = new \DateInterval('P1M');
//            $period = new \DatePeriod(
//                $startDate->modify('first day of this month'),
//                $interval,
//                $endDate->modify('first day of next month')
//            );

            $public_map = [
                ['is_cancel','=',0],
                ['service_id','=',$v['id']],
            ];

            $bj = $v['consume_money'];
            $zj = $v['consume_gratuity'];
            $dz = $v['consume_store_transfer'];

            /****************************次卡调整 begin***********************************/
            list($consume_money,$consume_gratuity,$consume_store_transfer,$lasttime_money,$lasttime_gift,$lasttime_storetransfer) = $serviceModel->lasttimeConsume($v);

            $alreadyCancel = Db::name('service_log')->where($public_map)->column('id');
            echo "服务卡项id: ". $v['id']. "<br>";
            $alreadyCancelCount = count($alreadyCancel);
            echo "已经核销次数: ". $alreadyCancelCount. "<br>";
            $num = $v['service_max_num'];
            echo "开卡次数: ". $num. "<br>";

            if(($consume_money<0.01&& $bj != 0 ) || ($consume_gratuity<0.01&& $zj!=0 ) || ($consume_store_transfer<0.01&& $dz != 0 ) ){
                if($num > $alreadyCancelCount){
                    for($i=1;$i<=$alreadyCancelCount;$i++){
                        $addData = [];
                        if($i == 1){

                        }else{
                            $addData['consume_gratuity'] = $consume_gratuity;
                            $addData['consume_money'] = $consume_money;
                            $addData['consume_store_transfer'] = $consume_store_transfer;
                        }


                        echo "需要调整服务卡项log 的金额: <br>";
                        print_r($addData);
                        echo "<br>";
                        DB::name('service_log')->where('id',$alreadyCancel[$i-1])->update($addData);
                    }
                }  else if($num < $alreadyCancelCount){

                }
            }else{
                if($num > $alreadyCancelCount){
                    //开卡次数大于已经核销次数
                    for($i=1;$i<=$alreadyCancelCount;$i++){
                        $addData = [];
                        $addData['consume_gratuity'] = $consume_gratuity;
                        $addData['consume_money'] = $consume_money;
                        $addData['consume_store_transfer'] = $consume_store_transfer;
                        echo "需要调整服务卡项log 的金额: <br>";
                        print_r($addData);
                        echo "<br>";
                        DB::name('service_log')->where('id',$alreadyCancel[$i-1])->update($addData);
                    }
                }
                else if($num < $alreadyCancelCount){
                    $diff  = bcsub($alreadyCancelCount,$num);

                    $diff_arr = $money_arr =  [];
                    foreach($alreadyCancel as $k=>$v){
                        if($k <$diff){
                            array_push($diff_arr,$v);
                        }else{
                            array_push($money_arr,$v);
                        }
                    }

                    foreach($diff_arr as $k=>$vv){
                        $addData = [];
                        $addData['consume_gratuity'] = 0;
                        $addData['consume_money'] = 0;
                        $addData['consume_store_transfer'] = 0;
                        DB::name('service_log')->where('id',$vv)->update($addData);
                    }

                    $money_arr_count = count($money_arr);
                    for($i=1;$i<=$money_arr_count;$i++){
                        $addData = [];
                        $addData['consume_gratuity'] = $consume_gratuity;
                        $addData['consume_money'] = $consume_money;
                        $addData['consume_store_transfer'] = $consume_store_transfer;
                        if($i == $money_arr_count){
                            $addData['consume_gratuity'] = $lasttime_gift;
                            $addData['consume_money'] = $lasttime_money;
                            $addData['consume_store_transfer'] = $lasttime_storetransfer;
                        }
                        echo "需要调整服务卡项log 的金额: <br>";
                        print_r($addData);
                        echo "<br>";
                        DB::name('service_log')->where('id',$money_arr_count[$i-1])->update($addData);
                    }
                }
                else{
                    //开卡次数与核销次数相等
                    for($i=1;$i<=$alreadyCancelCount;$i++){
                        $addData = [];
                        $addData['consume_gratuity'] = $consume_gratuity;
                        $addData['consume_money'] = $consume_money;
                        $addData['consume_store_transfer'] = $consume_store_transfer;
                        if($i == $alreadyCancelCount){
                            $addData['consume_gratuity'] = $lasttime_gift;
                            $addData['consume_money'] = $lasttime_money;
                            $addData['consume_store_transfer'] = $lasttime_storetransfer;
                        }
                        echo "需要调整服务卡项log 的金额: <br>";
                        print_r($addData);
                        echo "<br>";
                        DB::name('service_log')->where('id',$alreadyCancel[$i-1])->update($addData);
                    }
                }
            }




            echo "-------------------------<br>";
            /****************************次卡调整 end***********************************/

//            $service_end_year_month = date('Ym',$v['end_time']);
//
//            foreach ($period as $date) {
//                $monthStart = clone $date;
//                $monthEnd = clone $date;
//                $monthEnd->modify('last day of this month');
//                // 确保开始日期不早于给定的开始时间，结束日期不晚于给定的结束时间
//                if ($monthStart->getTimestamp() < $start_time) {
//                    $monthStart->setTimestamp($start_time);
//                }
//                if ($monthEnd->getTimestamp() > $end_time) {
//                    $monthEnd->setTimestamp($end_time);
//                }
//                echo "月份: ". $date->format('Y-m'). "<br>";
//                echo "开始日期: ". $monthStart->format('Y-m-d'). "<br>";
//                echo "结束日期: ". $monthEnd->format('Y-m-d 23:59:59'). "<br>";
//                $now_year_month = $date->format('Ym');
//                $benyue_begin_time = strtotime($monthStart->format('Y-m-d'));
//                $benyue_end_time = strtotime($monthEnd->format('Y-m-d  23:59:59'));
//
//                $logData['create_time'] = $benyue_begin_time;
//                $benyueCancel = $serviceModel->getMonthEnterShopNum($logData,$v); //本月最大进店次数
//                list($consume_money,$consume_gratuity,$consume_store_transfer,$lasttime_money,$lasttime_gift,$lasttime_storetransfer) = $serviceModel->lasttimeConsume($v);
//
//                echo "本月最大进店次数：".$benyueCancel."<br>";
//
//                $alreadyCancelCount = 0 ;
//                if($benyue_begin_time < 1746028800){
//                    $map = [
//                        ['create_time','>=',$benyue_begin_time],
//                        ['create_time','<=',$benyue_end_time]
//                    ];
//                    $alreadyCancel = Db::name('service_log')->where($public_map)->where($map)->column('id');
//                    echo "当月核销次数sql: ".  Db::name('service_log')->getlastsql(). "<br>";
//                    $alreadyCancelCount = count($alreadyCancel);
//                }
//                echo "已经核销次数: ". $alreadyCancelCount. "<br>";
//
//                if($alreadyCancelCount >0){
//                     if($service_end_year_month ==$now_year_month){
//                          for($i=1;$i<=$alreadyCancelCount;$i++){
//                            echo "需要调整服务卡项log 的id: ". $alreadyCancel[$i-1]. "<br>";
//                            $addData = [];
//                            $addData['consume_gratuity'] = 0;
//                            $addData['consume_money'] = 0;
//                            $addData['consume_store_transfer'] = 0;
//                            if($i < $benyueCancel){
//                                $addData['consume_gratuity'] = $consume_gratuity;
//                                $addData['consume_money'] = $consume_money;
//                                $addData['consume_store_transfer'] = $consume_store_transfer;
//                            }elseif($i == $benyueCancel){
//                                $addData['consume_gratuity'] = $lasttime_gift;
//                                $addData['consume_money'] = $lasttime_money;
//                                $addData['consume_store_transfer'] = $lasttime_storetransfer;
//                            }
//                            echo "需要调整服务卡项log 的金额: <br>";
//                            print_r($addData);
//                            echo "<br>";
//                            DB::name('service_log')->where('id',$alreadyCancel[$i-1])->update($addData);
//                        }
//                      }else{
//                          for($i=1;$i<=$alreadyCancelCount;$i++){
//                            echo "需要调整服务卡项log 的id: ". $alreadyCancel[$i-1]. "<br>";
//                            $addData = [];
//                            $addData['consume_gratuity'] = 0;
//                            $addData['consume_money'] = 0;
//                            $addData['consume_store_transfer'] = 0;
//                            if($i <= $benyueCancel){
//                                $addData['consume_gratuity'] = $consume_gratuity;
//                                $addData['consume_money'] = $consume_money;
//                                $addData['consume_store_transfer'] = $consume_store_transfer;
//                            }
//                            echo "需要调整服务卡项log 的金额: <br>";
//                            print_r($addData);
//                            echo "<br>";
////                            DB::name('service_log')->where('id',$alreadyCancel[$i-1])->update($addData);
//                          }
//                      }
//                }
//                echo "------------------------<br>";
//            }
        }
        var_dump($error);die;
    }


    public function verify_kkmoney(){

//        $cishu = 10;
//
//        $bj = 0;
//        $zj = 0.09;
//        $dz = 0;
//        $one_bj = bcdiv($bj,$cishu,2);
//        $one_zj = bcdiv($zj,$cishu,2);
//        $one_dz = bcdiv($dz,$cishu,2);
//        if(($one_bj<0.01&& $bj != 0 ) || ($one_zj<0.01&& $zj!=0 ) || ($one_dz<0.01&& $dz != 0 ) ){
//            echo 1;
//        }else{
//            echo 2;
//        }
//        die;


        $where_map = [
            ['status','=',1],
            ['type','<>',2],
            ['shop_id','<>',74076159037951],
        ];
        $shopids = DB::name('shop')->where($where_map)->column('shop_id');
        //先验证次卡
        $where =[
            ['status','=',1],
//            ['service_type','=','2'], //次卡
            ['service_type','=','1'], //疗程卡
            ['order_id','=',0],
            ['kk_money','=',0],
//            ['is_two_tz','=',3],
            ['shop_id','in',$shopids]
        ];

        $service = DB::name('service')->where($where)
            ->field('order_id,id,goods_id,customer_id,service_type,num,name,shop_id,id,start_time,end_time,order_id,create_time')
//            ->limit(100000,5000)
            ->select()->toArray();

//        var_dump(count($service));die;

        $service_arr= [];
        $error_goods = [];
        $update_service_ids = [];
        foreach($service as $k=>&$v){
            $maps = [
                ['type','=',1],
                ['update_id','=',$v['id']],
                ['customer_id','=',$v['customer_id']],
            ];
            $v['end_time'] = DB::name('update_log')->where($maps)->order('id')->value('old_date');
            array_push($service_arr,['customer_id'=>$v['customer_id'],'service_id'=>$v['id']]);
            $beging_time = strtotime(date('y-m-d'),$v['create_time']);
            $end_time   = strtotime(date('y-m-d 23:59:59'),$v['create_time']);
            $map = [
                ['a.uid','=',$v['customer_id']],
                ['b.goods_id','=',$v['goods_id']],
                ['a.create_time','between',"$beging_time,$end_time"],
//                ['a.id','=',$v['order_id']],
                ['b.is_project','=',2],
//                ['b.project_type','=',1],//次卡
//                ['b.service_number','=',$v['num']],
                                ['b.project_type','=',2],//疗程卡
                ['b.start_time','=',$v['start_time']],
                ['b.end_time','=',$v['end_time']],
                ['a.status','=',2]
            ];
            $data = DB::name('shop_order')->alias('a')
                ->leftJoin('shop_order_goods b','a.id=b.order_id')
                ->where($map)
                ->field('b.id as shop_order_goods_id,a.id,b.goods_id,b.pay_price,b.number,b.start_time,b.end_time')
                ->select()->toArray();
            $data_count = count($data);
            if($data_count > 0){
                $is_update = 0;
                foreach($data as $kk=>&$vv){
                    if($vv['pay_price'] >0){
                        $is_update++;
                    }
                    $vv['kk_money'] = bcmul($vv['number'],$vv['pay_price'],2);
                }
//                var_dump($data);
//                echo "-------------------------------------<br>";
                if($is_update>0){
                    // 要排序的字段
                    $sortField = 'kk_money';
                    // 使用 usort 函数进行排序
                    usort($data, function ($a, $b) use ($sortField) {
                        return $b[$sortField] <=> $a[$sortField];
                    });
                    $update = [
                        'kk_money' => $data[0]['kk_money'],
//                        'order_id'=>$data[0]['id'],
//                        'order_goods_id'=>$data[0]['shop_order_goods_id'],
                        'consume_money' =>$data[0]['kk_money'],
                        'is_two_tz' => 8,
                    ];
                    $res = DB::name('service')->where('id',$v['id'])->update($update);
                    if($res){
                        array_push($update_service_ids,$v['id']);
                    }
                }
            }
        }
//        echo "需调整的卡项ids：";
//        echo "<pre>";
//        print_r($service_arr);
        echo "<br>";
        echo "已经调整过的卡项ids：";
        echo "<pre>";
        print_r($update_service_ids);
        echo "<br>";
        echo "出现错误的商品ids：";
        echo "<pre>";
        print_r($error_goods);
        echo "<br>";
        echo "-------------------------------------";
        echo "<br>";

    }

    public function verify_kkmoney1(){
//        echo 111;die;

        if (empty($_FILES['file'])) {

            echo '请选择上传文件<br><br><a href="http://ddapi.liyinsheng.cn/return/yue.html">返回【会员基本信息-余额导入】页面</a>';exit;

        }

        $tmp_name = $_FILES['file']['tmp_name'];

        if (empty($tmp_name) || !file_exists($tmp_name)) {

            echo '请选择上传文件<br><br><a href="http://ddapi.liyinsheng.cn/return/yue.html">返回【会员基本信息-余额导入】页面</a>';exit;

        }

        $importData = readExcelData($tmp_name);

        $importData = array_values($importData);


        echo '表格中共计：'.count($importData).'条记录<br><br>';
        die;
//        var_dump($importData);die;

        $where_map = [
            ['status','=',1],
            ['type','<>',2],
            ['shop_id','<>',74076159037951],
        ];
        $shopids = DB::name('shop')->where($where_map)->column('shop_id');

        //先验证次卡
        $where =[
            ['status','=',1],
            ['service_type','=','2'], //次卡
//            ['service_type','=','1'], //疗程卡
            ['order_id','=',0],
            ['kk_money','=',0],
//            ['is_two_tz','=',3],
            ['shop_id','in',$shopids]
        ];

        $service = DB::name('service')->where($where)
            ->field('order_id,id,goods_id,customer_id,service_type,num,name,shop_id,id,start_time,end_time,order_id,create_time,name')
            ->select()->toArray();

//        var_dump(count($service));die;
//        $customer_id = DB::name('customer')->where('telephone','13520351725')->select()->toArray();
//        echo "<pre>";

        $update_service_ids = [];
        $error_customer = [];
        $update_error_service_ids = [];
        foreach ($importData as $key => $val){
                $map = [
                    ['telephone','=',$val[1]],
//                    ['shop_id','=',$val[10]],
                    ['shop_id','in',$shopids]
                ];
                $customer_id = DB::name('customer')->where($map)->value('id');
                if(!empty($customer_id) && $val[5] == '按次'){
                    foreach($service as $k=>$v){
                        $create_time = date('Y-m-d',$v['create_time']);
//                        if($v['name'] == $val[3] && $v['end_time'] == strtotime($val[7]) && $v['shop_id'] == $val[10] && $create_time == $val[0]  ){
                        if($v['name'] == $val[3] && $v['num'] == $val[6] && $v['shop_id'] == $val[10] && $create_time == $val[0]  ){

                            $update = [
                                'kk_money' => $val[4],
//                        'order_id'=>$data[0]['id'],
//                        'order_goods_id'=>$data[0]['shop_order_goods_id'],
                                'consume_money' =>$val[4],
                                'is_two_tz' => 9,
                            ];
                            $res = DB::name('service')->where('id',$v['id'])->update($update);
                            array_push($update_service_ids,$key);
                        }
                    }
                    array_push($update_error_service_ids,$key);
                }else{
                    array_push($error_customer,$key);
                }
            }

//        echo "<br>";
//        echo "顾客信息匹配中但无卡项信息的卡项ids：";
//        echo "<pre>";
//        print_r($update_error_service_ids);
        echo "<br>";
        echo "已经调整过的卡项ids：";
        echo "<pre>";
        print_r($update_service_ids);
        echo "<br>";
        echo "未匹配到的表中行数：";
        echo "<pre>";
        print_r($error_customer);
        echo "<br>";
        echo "-------------------------------------";
        echo "<br>";





//        $cishu = 10;
//
//        $bj = 0;
//        $zj = 0.09;
//        $dz = 0;
//        $one_bj = bcdiv($bj,$cishu,2);
//        $one_zj = bcdiv($zj,$cishu,2);
//        $one_dz = bcdiv($dz,$cishu,2);
//        if(($one_bj<0.01&& $bj != 0 ) || ($one_zj<0.01&& $zj!=0 ) || ($one_dz<0.01&& $dz != 0 ) ){
//            echo 1;
//        }else{
//            echo 2;
//        }
//        die;
    }

    //定时任务
    public function change_service_time(){

        $service = DB::name('service')->where('is_tz',0)->where('service_type',1)->where('status',1)->field('id,end_time')->select()->toArray();
        foreach ($service as $k=>&$v){
            if(!empty($v['end_time']) && $v['end_time'] >0){
                $end_time =  strtotime(date('Y-m-d 23:59:59',$v['end_time']));
                DB::name('service')->where('id',$v['id'])->update(['end_time'=>$end_time,'update_time'=>time()]);
            }
        }
        echo "执行成功";die;
    }

    public function sendyxk(){

        $data = DB::name('shop_order')->where('api_type',0)->where('status',2)->select()->toArray();
        $customerModel = new \app\crm\model\Customer();
        foreach($data as $k=>$v){
            $res = $customerModel->pushKingCustomer($v['uid']);
            if($res == false){
                $this->error = $customerModel->getError();
                return false;
            }
            $kingDee = new Kingdee();
            //出库单-四个订单录入的
            $result=$kingDee->send_order($v['id']);
            //销售出库单订单-核销产生的订单/出预存货的订单
//            $result=$kingDee->send_service_prestock_order($v['id']);
//            //销售出库单订单-病例开单拆出来的出库单
//            $result=$kingDee->send_case_order($v['id']);
            if ($result['code'])
            {
                $this->error = $result['msg'];
                return false;
            }
        }
        die;

    }







}
